import { useRequest } from 'ahooks';
import request from '@/utils/request';

function flattenTree(treeNodes) {
  if (!treeNodes) {
    return [];
  }
  const nodeList = [];
  const generateList = nodes => {
    nodes.forEach(node => {
      nodeList.push(node);
      if (node.children) {
        generateList(node.children);
      }
    });
  };
  generateList(treeNodes);
  return nodeList;
}

function useCatalogTree(code, options = { withLeaves: false }) {
  const { withLeaves } = options;

  const { data = [], loading, run: refresh } = useRequest(() =>
    request.get(`/${code}/listCatalogTree?withLeaves=${withLeaves}`)
  );

  const nodeList = flattenTree(data);

  return { data, nodeList, loading, refresh };
}

export default useCatalogTree;
